package com.mzy.linear_struct.subject;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: codermzy
 * @Date: 2024/04/25/下午5:38
 * @Description:
 */
public class 两个线程交替打印ReentrantLock {

    public static final Lock lock = new ReentrantLock();
    public static boolean printNumber = false;

    public static void main(String[] args) {
        // Condition condition = lock.newCondition();
        // Thread t1 = new Thread(() -> {
        //     for (int i = 1; i <= 3; i++) {
        //         lock.lock();
        //         try {
        //             System.out.print(i);
        //             condition.signal(); // 唤醒打印字母的线程
        //             if (i < 3) {
        //                 condition.await(); // 等待打印字母的线程执行
        //             }
        //         } catch (InterruptedException e) {
        //             Thread.currentThread().interrupt();
        //         } finally {
        //             lock.unlock();
        //         }
        //     }
        //
        //
        // });
        //
        // Thread t2 = new Thread(() -> {
        //     for (char letter = 'A'; letter <= 'C'; letter++) {
        //         lock.lock();
        //         try {
        //             System.out.print(letter);
        //             condition.signal(); // 唤醒打印数字的线程
        //             if (letter < 'C') {
        //                 condition.await(); // 等待打印数字的线程执行
        //             }
        //         } catch (InterruptedException e) {
        //             Thread.currentThread().interrupt();
        //         } finally {
        //             lock.unlock();
        //         }
        //     }
        // });

        Condition condition = lock.newCondition();

        Thread t1 = new Thread(() -> {


            for (char c = 'A'; c <= 'C'; c++) {
                    lock.lock();
                try {
                    while (!printNumber) {
                        condition.await();
                    }
                    System.out.println(c);
                    printNumber = true;
                    condition.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }


        });

        Thread t2 = new Thread(() -> {

            for (int i = 1; i <= 3; i++) {
                try {
                    lock.lock();

                    while (printNumber) {
                        condition.await();
                    }
                    System.out.println(i);
                    printNumber = false;
                    condition.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }


        });

        t1.start();
        t2.start();


    }
}
